from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
from backend.database import SessionLocal
from backend.models import Application, User, JobPosting
from backend.schemas import ApplicationCreate, ApplicationResponse, ApplicationUpdate
import logging

# 日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter(prefix="")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 获取申请列表
@router.get("/api/applications", response_model=List[ApplicationResponse])
async def get_applications(
    applicant_id: Optional[int] = Query(None),
    job_id: Optional[int] = Query(None),
    db: Session = Depends(get_db)
):
    """
    获取申请，可以根据applicant_id或job_id过滤
    """
    query = db.query(Application)
    if applicant_id is not None:
        query = query.filter(Application.applicant_id == applicant_id)
    if job_id is not None:
        query = query.filter(Application.job_id == job_id)
    apps = query.order_by(Application.apply_time.desc()).all()
    return apps

# 创建新申请
@router.post("/api/applications", response_model=ApplicationResponse)
async def create_application(
    application: ApplicationCreate,
    applicant_id: int = Query(..., description="申请人用户ID"),
    db: Session = Depends(get_db)
):
    """
    创建新的职位投递申请
    """
    # 验证用户和职位存在
    user = db.query(User).filter(User.user_id == applicant_id).first()
    if not user:
        logger.warning(f"申请人不存在: applicant_id={applicant_id}")
        raise HTTPException(status_code=404, detail="申请人不存在")
    job = db.query(JobPosting).filter(JobPosting.job_id == application.job_id).first()
    if not job:
        logger.warning(f"职位不存在: job_id={application.job_id}")
        raise HTTPException(status_code=404, detail="职位不存在")

    # 创建申请
    db_app = Application(
        job_id=application.job_id,
        applicant_id=applicant_id,
        apply_time=datetime.utcnow(),
        status=application.status if hasattr(application, 'status') else None,
        cover_letter=application.cover_letter
    )
    db.add(db_app)
    db.commit()
    db.refresh(db_app)
    logger.info(f"成功创建申请: application_id={db_app.application_id}")
    return db_app

# 添加更新申请状态的接口
@router.put("/api/applications/{application_id}", response_model=ApplicationResponse)
async def update_application(application_id: int, update_data: ApplicationUpdate, user_id: int = Query(..., description="招聘者用户ID"), db: Session = Depends(get_db)):
    app_record = db.query(Application).filter(Application.application_id == application_id).first()
    if not app_record:
        raise HTTPException(status_code=404, detail="申请不存在")
    job_post = db.query(JobPosting).filter(JobPosting.job_id == app_record.job_id).first()
    if not job_post:
        raise HTTPException(status_code=404, detail="职位不存在")
    if job_post.user_id != user_id:
        raise HTTPException(status_code=403, detail="无权限修改此申请状态")
    app_record.status = update_data.status
    db.commit()
    db.refresh(app_record)
    return app_record 